import json
import os
import ssl
import time
import random
import threading
import paho.mqtt.client as mqtt
import settings

mqtthost = settings.mqtthost
mqttport = int(settings.mqttport)
mqttuser = settings.mqttuser
mqttpwd = settings.mqttpassword
mqttTLS = settings.mqttTLS

work_topic = '/device/work'
work_staus_topic = '/work/status'


def start_work(uuid):
    # 这里时开始工作
    num = random.randint(30, 60)
    time.sleep(num)
    # 工作结束
    data = {"uuid": uuid, "status": 0}
    client.publish(work_staus_topic, json.dumps(data))


def stop_work(uuid):
    # 停止工作
    pass


def msg_process(topic, data):

    if topic == work_topic:
        data = json.loads(data)
        uuid = data.get('uuid')
        status = data.get('status')
        if status == 1:
            # 执行代码，这里去根据对应的设备让其工作起来
            threading.Thread(target=start_work, args=[uuid, ]).start()
            # 执行成功后,表示开始工作
            data = {"uuid": uuid, "status": 1}
            client.publish(work_staus_topic, json.dumps(data))
        elif status == 0:
            # 执行代码，这里去根据对应的设备让其停止工作
            threading.Thread(target=stop_work, args=[uuid, ]).start()
            # 执行成功后，表示停止工作
            data = {"uuid": uuid, "status": 0}
            client.publish(work_staus_topic, json.dumps(data))



def on_connect(client, userdata, flags, rc):
    print('mqtt链接')
    # client.subscribe("/test/")
    # client.subscribe("/room/online")
    client.subscribe(work_topic)


def on_message(client, userdata, msg):
    # print(msg.topic,msg.payload.decode('utf-8'))
    # 处理消息
    msg_process(msg.topic, msg.payload.decode('utf-8'))


def on_subscribe(client, userdata, mid, granted_qos):
    print('订阅')
    # print("On Subscribed: qos = %d" % granted_qos)


def on_disconnect(client, userdata, rc):
    print('断开链接')
    # if rc != 0:
    #     print("Unexpected disconnection %s" % rc)


client = mqtt.Client()
client.username_pw_set(mqttuser, mqttpwd)
client.on_connect = on_connect
client.on_message = on_message
client.on_subscribe = on_subscribe
client.on_disconnect = on_disconnect
# client.connect(HOST, PORT, 60)

if mqttTLS:

    path = os.getcwd() + '/wchime.xyz_bundle.crt'
    client.tls_set(path, cert_reqs=ssl.CERT_NONE, tls_version=ssl.PROTOCOL_TLSv1_2)
    client.tls_insecure_set(True)
client.connect_async(host=mqtthost, port=mqttport, keepalive=60, bind_address="")
# client.loop_forever()
client.loop_start()









